/**
 * Created by aboc on 17-1-3.
 */
function canvas_album(){

    this.start = {x:0,y:0};
    this.touch_point = {x:0,y:0};
    this.last_touch_size = 0;
    this.is_move = false;
    this.is_wheel = false;
    this.click_time = 0;
    this.click_callback = null;
    this.touchs = 0;

    this.imgs = new Array();
    var o = this;

    this.edit = false;


    this._draw = function(dom,src,width,height,left,top,scale,points,index){
        var canvas = document.getElementById(dom);
        if(canvas == null){
            alert(dom +" 不存在");
            return;
        }
        function complete_drag(e,touch) {
            //console.info(o.touchs);
            if ( (o.is_move) && o.edit) {
                //console.info(e);
                if(touch){
                    var offset_x = o.start.x - o.touch_point.x;
                    var offset_y = o.start.y - o.touch_point.y;
                } else {
                    var offset_x = o.start.x - e.x;
                    var offset_y = o.start.y - e.y;
                    canvas.style.cursor = "inherit";
                }
                o.imgs[index].left += offset_x;
                o.imgs[index].top += offset_y;
                o.imgs[index].state = 1;
                o.is_move = false;
            }
            if( ((new Date()).getTime() - o.click_time) < 150  && (!touch  || e.targetTouches.length == 1 || typeof  e.targetTouches.length == "undefined")){
                o.click_time = 0;
                o.is_move = false;
                if(o.click_callback!=null && o.edit){
                    eval(o.click_callback).call({}, o.imgs[index]);
                    return;
                }
            }
        }

        function start_drag(e,touch) {
            o.click_time = (new Date()).getTime();
            if (o.edit) {
                if(touch){
                    o.start.x = e.targetTouches[0].clientX;
                    o.start.y = e.targetTouches[0].clientY;
                } else {
                    o.start.x = e.x;
                    o.start.y = e.y;
                    canvas.style.cursor = "pointer";
                }
                o.is_move = true;
            }
        }

        function draging(e, touch) {
            if (o.is_move && o.edit) {
                if(o.imgs[index].src == "images/adf_upload_img.png"){
                    return;
                }
                o.imgs[index].state = 1;
                if(touch){
                    this.touchs = e.targetTouches.length;
                    if(e.targetTouches.length>1){
                        //缩放
                        var now_size = Math.sqrt(Math.pow(Math.abs((e.targetTouches[0].clientX - e.targetTouches[1].clientX)),2) + Math.pow(Math.abs((e.targetTouches[0].clientY - e.targetTouches[1].clientY)),2));
                        //var abs = Math.abs(now_size - o.last_touch_size);
                        if( now_size > o.last_touch_size ){
                            //放大
                            o.imgs[index].scale -= now_size/ o.last_touch_size*0.1;
                            //o.imgs[index].left -= abs;
                            //o.imgs[index].top -= abs;
                        }  else {
                            //缩小
                            o.imgs[index].scale += now_size/ o.last_touch_size*0.05;
                            //o.imgs[index].left += abs;
                            //o.imgs[index].top += abs;
                        }
                        if(o.imgs[index].scale <= 0.1){
                            o.imgs[index].scale = 0.1;
                        }
                        if(o.imgs[index].scale >=5){
                            o.imgs[index].scale = 5;
                        }
                        o.debug(o.imgs[index].scale);
                        o.last_touch_size = now_size;
                        drawimage(canvasImage, width, height, o.imgs[index].left, o.imgs[index].top, o.imgs[index].scale);
                        return;
                    }
                    var offset_x = o.start.x - e.targetTouches[0].clientX;
                    var offset_y = o.start.y - e.targetTouches[0].clientY;
                    o.touch_point.x =  e.targetTouches[0].clientX;
                    o.touch_point.y =  e.targetTouches[0].clientY;
                } else {
                    var offset_x = o.start.x - e.x;
                    var offset_y = o.start.y - e.y;
                }

                //limit left or top
                if( (o.imgs[index].left + offset_x) < 0){
                    offset_x = 0 - o.imgs[index].left;
                }
                if( (o.imgs[index].top + offset_y) < 0){
                    offset_y = 0 - o.imgs[index].top;
                }
                var temp_height =( o.imgs[index].image.height - o.imgs[index].height) > 0 ? (o.imgs[index].image.height - o.imgs[index].height) : o.imgs[index].height ;
                if( (o.imgs[index].top + offset_y ) > (  temp_height  )){
                    offset_y = temp_height - o.imgs[index].top;
                }
                var temp_width =( o.imgs[index].image.width - o.imgs[index].width) > 0 ? (o.imgs[index].image.width - o.imgs[index].width) : o.imgs[index].width ;
                if( (o.imgs[index].left + offset_x ) > (  temp_width  )){
                    offset_x = temp_width - o.imgs[index].left;
                }
                //end limit
                o.imgs[index].left += offset_x;
                o.imgs[index].top += offset_y;
                drawimage(canvasImage, width, height, o.imgs[index].left, o.imgs[index].top, o.imgs[index].scale);
                o.stopPropagation(e);
            }
        }

        function wheel(e) {
            if (o.edit) {
                drawimage(canvasImage, width, height, o.imgs[index].left, o.imgs[index].top, o.imgs[index].scale);
                o.is_wheel = true;
                o.stopPropagation(e);
            }
        }

        if (canvas.getContext) {
            var canvasImage = new Image();
            canvasImage.src = src;
            var ctx = canvas.getContext("2d");
            var drawimage = function (canvasImage, width, height, left, top, scale) {
                if(canvas_album.imgs[index].state == 2){
                    //不重新渲染
                    return;
                }
                //保存画布当前状态
                // ctx.save();
                ctx.clearRect(0, 0, width, height);
                //开始一个新的绘制路径
                ctx.beginPath();
                //设置线条颜色为蓝色
                ctx.strokeStyle = "red";
                //设置路径起点坐标
                for(var i in points){
                    if(i == 0){
                        ctx.moveTo(points[i][0], points[i][1]);
                    } else {
                        ctx.lineTo(points[i][0], points[i][1]);
                    }
                    //console.log("Dom:",dom,points[i][0], points[i][1]);
                }
                ctx.closePath();
                ctx.clip();
                //if(src != "images/adf_upload_img.png") {
//      ctx.drawImage(canvasImage, 0, 0,930,522,0,0,296,518);
                ctx.drawImage(canvasImage, left, top, width * scale, height * scale, 0, 0, width, height);
                //}
                ctx.restore();
                canvas_album.imgs[index].state = 2; //渲染完成
                layer.closeAll();
            };
            //必须图片加载完后在进行绘图
            canvasImage.onload = function () {
                o.imgs[index].image = {width:canvasImage.width,height:canvasImage.height};
                drawimage(this, width, height, left, top, scale);
            };
            canvas.addEventListener("mousedown", function (e) {
                if(index == 4){
                    //canvas.style.pointerEvents = "none";
                    //return;
                }
                start_drag(e,false);
            }, false);
            canvas.addEventListener("touchstart", function (e) {
                start_drag(e,true);
            }, false);
            canvas.addEventListener("mousemove", function (e) {
                draging(e,false);
            }, false);
            canvas.addEventListener("touchmove", function (e) {
                //console.info(e)
                draging(e,true);
            }, false);
            canvas.addEventListener("mouseup", function (e) {
                complete_drag(e,false);
            }, false);
            canvas.addEventListener("touchend", function (e) {
                complete_drag(e,true);
            }, false);
            canvas.addEventListener("mouseout", function (e) {
                complete_drag(e,false);
            }, false);
            canvas.addEventListener("mousewheel", function (e) {
                o.imgs[index].scale += (e.deltaY > 0 ? -0.02 : 0.02);
                if(o.imgs[index].scale <= 0.3){
                    o.imgs[index].scale = 0.3;
                }
                if(o.imgs[index].scale >=3){
                    o.imgs[index].scale = 3;
                }
                o.imgs[index].state = 1;
                wheel(e);
            }, false);
        }
    }

    /**
     * 阻止冒泡
     * @param e
     */
    o.stopPropagation = function(e) {
        return;
        e = e || window.event;
        if(e.stopPropagation) { //W3C阻止冒泡方法
            e.stopPropagation();
        } else {
            e.cancelBubble = true; //IE阻止冒泡方法
        }
    }


    this.draw = function(){
        for(var i in o.imgs){
            o._draw(o.imgs[i].dom,o.imgs[i].src,o.imgs[i].width,o.imgs[i].height,o.imgs[i].left,o.imgs[i].top,o.imgs[i].scale,o.imgs[i].points,i);
        }
        document.body.addEventListener('touchmove', function(evt) {
            if(o.is_move || o.is_wheel) {
                evt.preventDefault();
            }
        });
        document.body.addEventListener('mousewheel', function(evt) {
            if(o.is_move || o.is_wheel) {
                evt.preventDefault();
            }
        });
    }

    this.deal_scale = function(scale){
        $("#pic-box").width("100%");
        $("#pic-box").height($("#pic-box").width()/414*652);
        for(var i in o.imgs){
            o.imgs[i].width =  parseInt(o.imgs[i].width *scale);
            o.imgs[i].height = parseInt(o.imgs[i].height * scale);
            //o.imgs[i].scale = parseFloat(o.imgs[i].scale *scale);
            if(o.imgs[i].scale<=0){
                o.imgs[i].scale = 0.5;
            }
            var obj = document.getElementById(o.imgs[i].dom);
            obj.width = o.imgs[i].width;
            obj.height = o.imgs[i].height;
            var left = obj.style.left;
            var top = obj.style.top;
            if(left != ""){
                obj.style.left = parseFloat(obj.style.left)*scale+"px";
            }
            if(top != ""){
                obj.style.top = parseFloat(obj.style.top)*scale+"px";
            }
            for(var k in o.imgs[i].points){
                o.imgs[i].points[k][0] = parseInt(o.imgs[i].points[k][0]  * scale);
                o.imgs[i].points[k][1] = parseInt(o.imgs[i].points[k][1] *scale);
            }
        }
    }
    this.debug = function(str){
        var d = document.getElementById("debug_info");
        if(d != null){
            d.innerText = "Debug:"+str;
        }
    }
}